const express = require("express");
const axios = require("axios");
const cookieParser = require("cookie-parser");
const Users = require("../db/models/users");
const { SuccessModal, ErrorModal } = require("../model");
const md5 = require("../utils/md5");
const { sign, verify } = require("../utils/jwt");
const { CLIENT_ID, CLIENT_SECRET } = require("../config");
const { filterPassword } = require("../utils/tools");
const session_user = require("../session");
const { nanoid } = require('nanoid')
const Router = express.Router;
const router = new Router();
const COOKIE_MAX_AGE = 7 * 24 * 3600 * 1000;

const { SocialiteManager } = require('node-socialite');
// wx.open.app_id=wxed9954c01bb89b47
// wx.open.app_secret=a7482517235173ddb4083788de60b90e
// #回调地址
// wx.open.redirect_url=http://localhost:8160/api/user/wx/callback
let manager = new SocialiteManager({
    wechat: {
        client_id: 'wxed9954c01bb89b47',
        client_secret: 'a7482517235173ddb4083788de60b90e',
        redirect: 'http://localhost:8160/api/user/wx/callback',
    },
});

router.get('/wechat/login', async (req, res) => {
    let url = manager.create('wechat').redirect();
    res.redirect(url);
});

//微信登录
router.get("/api/user/wx/callback", async (req, res) => {
    try {
        //获取到了授权码code
        const { code } = req.query;

        let data = await manager.create('wechat').userFromCode(code);

        console.log(data);
        
        //去数据库中查询是否存在该用户
        const user = await Users.findOne({ username: data.name });
        console.log(user);
        //准备一个token
        let token;
        //如果没有该用户
        if (!user) {
            //注册该用户，同时生成一个token
            token = await sign({ username: data.name });
            //向数据库中写入数据
            await Users.create({
                username: data.name,
                avatar: data.avatar,
                nickName: data.nickname,
                password: data.id,
                token: token,
                phone: 'github-' + nanoid(),
            });
        } else {
            //如果有该用户
            try {
                //取出之前存的token
                token = user.token;
                //校验token，看是否过期
                await verify(user.token);
            } catch {
                //若过期，重新生成token
                token = await sign({ username: data.id });
                //更改之前存储的token
                user.token = token;
                //保存数据
                await user.save();
            }
        }
        res.cookie("user_token", token, { maxAge: COOKIE_MAX_AGE });
        //将得到的用户数据返回到页面上~
        res.redirect(`http://localhost:3000/usercenter`);
    } catch (e) {
        console.log(e);
    }
});


module.exports = router;